/**
 * 
 */
package com.ssm.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssm.dao.AppointDao;
import com.ssm.dao.BookDao;
import com.ssm.entity.Appointment;
import com.ssm.entity.Book;
import com.ssm.enums.AppointStateEnum;
import com.ssm.exception.AppointException;
import com.ssm.exception.AppointExecution;
import com.ssm.exception.NonumberException;
import com.ssm.exception.ReaptAppointException;
import com.ssm.service.BookService;

/**
 * @author xieqiang_daye
 *
 */
@Service
public class BookServiceImpl implements BookService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//springIOC依赖注入
	@Autowired 
	private BookDao bookDao;
	@Autowired 
	private AppointDao appointDao;
	
	
	public Book getById(long bookId) {
		// TODO Auto-generated method stub
		return bookDao.queryById(bookId);
	}

	public List<Book> getList() {
		// TODO Auto-generated method stub
		return bookDao.queryAll(0, 1000);
	}
    
	@Transactional
	public AppointExecution appoint(long bookId, long studentId) {
		// TODO Auto-generated method stub
		try{
			//减少库存
		    int update = bookDao.reduceNumber(bookId);
		    if(update<=0){
		    	throw new AppointException("no number");
		    }else{
		    Appointment appointment = appointDao.queryByKeyWithBook(bookId, studentId);
		    return new AppointExecution(bookId, AppointStateEnum.SUCESS,appointment);
		    }
		}catch(NonumberException e1){
			throw e1;
		}catch(ReaptAppointException e2){
			throw e2;
		}catch(Exception e){
			logger.error(e.getMessage());
            throw new AppointException("appoint inner error:"+e.getMessage());
		}
	
	}

}
